package com.leyou.sh.item.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.sh.common.dto.PageDTO;
import com.leyou.sh.common.exception.LyException;
import com.leyou.sh.item.dto.BrandDTO;
import com.leyou.sh.item.entity.CategoryBrand;
import com.leyou.sh.item.service.CategoryBrandService;
import com.leyou.sh.item.entity.Brand;
import com.leyou.sh.item.mapper.BrandMapper;
import com.leyou.sh.item.service.BrandService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author balisong_fcs
 * @date 2020/12/27 19:45
 * @desc
 */
@Service
public class BrandServcieImpl extends ServiceImpl<BrandMapper, Brand> implements BrandService {
    @Autowired
    private CategoryBrandService categoryBrandService;

    @Override
    public BrandDTO queryBrandById(Long id) {
        return new BrandDTO(this.getById(id));
    }

    @Override
    public List<BrandDTO> queryBrandListByIds(List<Long> ids) {
        return BrandDTO.convertEntityList(this.listByIds(ids));
    }

   /* @Override
    public PageDTO queryByPage(Integer page, Integer rows, String key) {
        QueryWrapper<Brand> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(key)) {
            queryWrapper.and(wrapper -> {
                wrapper.like("name", key).or()
                        .like("letter", key);
            });
        }
        IPage<Brand> result = this.page(new Page<>(page, rows), queryWrapper);

        return new PageDTO(result.getTotal(), result.getPages(), BrandDTO.convertEntityList(result.getRecords()));
    }*/
   @Override
   public PageDTO<BrandDTO> queryByPage(Integer page, Integer rows, String key) {
       // 1.分页信息的健壮性处理
       page = Math.min(page, 100);
       rows = Math.max(rows, 5);
       // 2.分页
       Page<Brand> info = new Page<>(page, rows);
       // 3.判断key是否存在
       boolean isKeyExists = StringUtils.isNoneBlank(key);
       // 4.如果key存在，添加like和eq的查询条件，否则不添加
       query().like(isKeyExists, "name", key)
               .or()
               .eq(isKeyExists, "letter", key)
               .page(info);
       // 5.封装结果
       List<Brand> list = info.getRecords();
       return new PageDTO<>(info.getTotal(), info.getPages(), BrandDTO.convertEntityList(list));
   }

    @Override
    public List<BrandDTO>  queryBrandByCategroyId(Integer id) {
        List<CategoryBrand> categoryBrands = categoryBrandService.query().eq("category_id", id).list();
        if (CollectionUtils.isEmpty(categoryBrands)) {
            return Collections.emptyList();
        }
        List<Integer> brandIds = categoryBrands.stream().map(CategoryBrand::getBrandId).collect(Collectors.toList());
        return BrandDTO.convertEntityList(this.listByIds(brandIds));
    }

    @Override
    @Transactional
    public void updateBrand(BrandDTO brandDTO) {
        boolean result = this.updateById(brandDTO.toEntity(Brand.class));
        if (!result) {
            throw new LyException(500, "更新品牌失败");
        }
        //删除之前关联信息
        result = categoryBrandService.remove(new QueryWrapper<CategoryBrand>().eq("brand_id", brandDTO.getId()));
        if (!result) {
            throw new LyException(500, "更新品牌失败,删除中间表数据失败");
        }
        //重新维护分类品牌之间关系
        List<CategoryBrand> list = brandDTO.getCategoryIds().stream().map(id -> CategoryBrand.of(id, brandDTO.getId())).collect(Collectors.toList());
        categoryBrandService.saveBatch(list);
    }

    @Override
    public void deleteByBrandId(Integer id) {
        this.removeById(id);
        categoryBrandService.remove(new QueryWrapper<CategoryBrand>().eq("brand_id", id));
    }

    /**
     * 新增品牌
     * @param brandDTO
     */
    @Override
    @Transactional
    public void saveBrand(BrandDTO brandDTO) {
        //新增品牌
        Brand brand = brandDTO.toEntity(Brand.class);
        save(brand);
        //维护品牌分类的中间表
        List<CategoryBrand> list = brandDTO.getCategoryIds().stream().map(id -> CategoryBrand.of(id, brand.getId())).collect(Collectors.toList());
        categoryBrandService.saveBatch(list);

    }
}
